package com.yd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.doman.*;
import com.payutil.MyWXPayConfig;
import com.payutil.WXPay;
import com.payutil.WXPayConstants;
import com.payutil.WXPayUtil;
import com.resultmsg.BaseEnums;
import com.resultmsg.Result;
import com.resultmsg.Results;
import com.server.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yd.WxAuthController.httpsRequestToJsonObject;

@RequestMapping(value = "/educloud")
@RestController
public class PayController {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private ComboMapper comboMapper;
    @Autowired
    private TeacherParentMapper teacherParentMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ParentMapper parentMapper;
    @Autowired
    private BaseConfigMapper baseConfigMapper;
    @Autowired
    private PayOrdersMapper payOrdersMapper;


    //获取学生套餐
    @RequestMapping("/payYu")
    public Result payYu(String organize) {
        //查询租户
        Tenant tenant = new Tenant();
        tenant.setTenantId(organize);
        Tenant tenant1 = tenantMapper.selectByPrimaryByOrganize(tenant);
        if (tenant != null) {
            //查询套餐
            Combo combo = new Combo();
            combo.setKcode(tenant1.getOrderType());
            Combo combo1 = comboMapper.selectByPrimaryByKcode(combo);
            if (combo != null) {
                return Results.successWithData(combo1, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            } else {
                return Results.successWithData("", BaseEnums.FORBIDDEN.code(), BaseEnums.FORBIDDEN.desc());
            }
        }
        return Results.successWithData("", BaseEnums.FORBIDDEN.code(), BaseEnums.FORBIDDEN.desc());
    }

    @RequestMapping("/payNotifyUrl")
    public String payNotifyUrl(HttpServletRequest request) throws Exception {
//        ServletInputStream inputStream = request.getInputStream();
//        StringBuffer buf = new StringBuffer();
//        String s;
//        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
////        WXPayUtil.xmlToMap(inputStream);
//        while ((s = in.readLine()) != null) {
//            buf.append(s);
//        }
//        in.close();
//        inputStream.close();
//        System.err.println(buf);
//        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(String.valueOf(buf));


//        PayOrders payOrders = new PayOrders();
//        Parent parent = new Parent();
//        parent.setOpenid("o0fM1w8QJwxPa26YrpGtz7lh1Cdo");
//        Parent parent1 = parentMapper.selectByPrimaryByOpenid(parent);
//        //查询学生信息返回
//        Student student = new Student();
//        student.setBindcode(parent1.getCurrentcode());
//        Student student1 = studentMapper.selectByPrimaryByCurrentCode(student);
//        //修改华栖云数据先登录
//        String token_url = "https://yjapp.h5.kecheng.zhixue100.com.cn/userapi/v1/loginbycode?account=" + student1.getBindcode() + "&password=Klmb321hbwx&tenant_id=" + student1.getOrganize() + "&bindcode=" + student1.getBindcode();
//        net.sf.json.JSONObject access_token = httpsRequestToJsonObject(token_url, "POST", null);
//        String data1 = access_token.getString("params");
//        com.alibaba.fastjson.JSONObject jsondata = JSON.parseObject(data1);
//        String token = jsondata.getString("token");
//
//
//
//
//
//
//
//
//        //查询租户
//        Tenant tenant = new Tenant();
//        tenant.setTenantId(student1.getOrganize());
//        Tenant tenant1 = tenantMapper.selectByPrimaryByOrganize(tenant);
//        //查询套餐
//        Combo combo = new Combo();
//        combo.setKcode(tenant1.getOrderType());
//        Combo combo1 = comboMapper.selectByPrimaryByKcode(combo);
//        //添加支付失效时间
//        switch (combo1.getComboType()) {
//            case 0:
//                payOrders.setExpiretime(plusDay(30));
//                break;
//            case 1:
//                payOrders.setExpiretime(plusDay(90));
//                break;
//            case 2:
//                payOrders.setExpiretime(plusDay(365));
//                break;
//            case 3:
//                payOrders.setExpiretime(plusDay(3));
//                break;
//        }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//        HttpClient client = HttpClients.createDefault();
//        // 修改华栖云支付状态
//        String url = "https://yjapi.kecheng.zhixue100.com.cn/userapi/v1/memberupdate/" + parent1.getCurrentcode();
//        HttpPost post = new HttpPost(url);
//        JSONObject jsonObject = null;
//        try {
//            JSONObject json = new JSONObject();
//            json.put("pay_status", 1);
//            long time = payOrders.getExpiretime().getTime();
//            int s = (int) (time /1000);
//            json.put("expire", s);
//            StringEntity s2 = new StringEntity(json.toString());
//            s2.setContentEncoding("UTF-8");
//            s2.setContentType("application/json");
//            post.setEntity(s2);
//            post.addHeader("Authorization", "Bearer " + token);
//            HttpResponse res = client.execute(post);
//            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
//                jsonObject = JSONObject.parseObject(result);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        System.err.println(jsonObject);
//        if (jsonObject.get("message").equals("编辑用户成功")) {
//            //商户订单号
//            payOrders.setGoodsorder("20211617172221681");
//            //腾讯返回订单号
//            payOrders.setWeixinorder("123");
//            //微信用户唯一标识
//            payOrders.setOpenid("o0fM1w8QJwxPa26YrpGtz7lh1Cdo");
//            //修改用户为支付用户
//            payOrders.setPaytype("1");
//            //修改学生表学生支付状态
//            student1.setPayStatus(1);
//            //修改学生表之支付状态
//            int updateByPrimaryKeySelective = studentMapper.updateByPrimaryKeySelective(student1);
//            //修改订单表支付状态
//            int insertSelective = payOrdersMapper.updateByPrimaryKeySelectiveOpenidAndGoodorder(payOrders);
//            //返回微信成功信息xml格式
//            Map<String, String> map = new HashMap<>();
//            map.put("return_code","SUCCESS");
//            map.put("return_msg","OK");
//            String s1 = WXPayUtil.mapToXml(map);
//            return s1;
//        }
        return "";
    }




    @RequestMapping("/craetePay")
    public Result createOrder(String openid, String price) throws Exception {
        System.err.println(new Date().getTime() / 1000);
        MyWXPayConfig config = new MyWXPayConfig();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "智学100");//充值内容-暂时静态
        String s = "2021" + WXPayUtil.getCurrentTimestampMs();
        data.put("out_trade_no", s);//获取当前时间+时间戳
        double num;
        java.text.DecimalFormat myformat = new java.text.DecimalFormat("#0.00");
        num = Double.parseDouble(price);//装换为double类型
        num = Double.parseDouble(myformat.format(num));//保留2为小数
        data.put("total_fee", getDoubleString(num * 100));//动态
        data.put("spbill_create_ip", "123.12.12.123");//动态
        data.put("notify_url", "https://zxyb.zhixue100.com.cn/educloud/craetePayUpdate");//静态
//        data.put("notify_url", "http://27.184.189.21:9100/educloud/craetePayUpdate");

        data.put("trade_type", "JSAPI");//静态
        data.put("openid", openid);//openid-动态
//        System.err.println();
        //生成订单
        TeacherParent teacherParent = new TeacherParent();
        teacherParent.setOpenid(openid);
        //查询用户是否是绑定用户
        TeacherParent teacherParent1 = teacherParentMapper.selectByPrimaryKeyOpenid(teacherParent);
        //判断平台信息是否为空,不为空的话进行跳转
        if (teacherParent1 != null) {
            if (teacherParent1.getPlatforms().equals("2")) {
                PayOrders payOrders = new PayOrders();
                payOrders.setCreatetime(new Date());
                payOrders.setOpenid(teacherParent.getOpenid());
//                payOrders.setExpiretime();
                //查询家长信息
                if (teacherParent.getOpenid() != null) {
                    Parent parent = new Parent();
                    parent.setOpenid(teacherParent1.getOpenid());
                    Parent parent1 = parentMapper.selectByPrimaryByOpenid(parent);
                    payOrders.setParenttal(parent1.getTel());
                    //查询学生信息返回
                    Student student = new Student();
                    student.setBindcode(parent1.getCurrentcode());
                    Student student1 = studentMapper.selectByPrimaryByCurrentCode(student);
                    payOrders.setStudentcode(student1.getBindcode());
                    payOrders.setStudentname(student1.getName());
                    //查询租户
                    Tenant tenant = new Tenant();
                    tenant.setTenantId(student1.getOrganize());
                    Tenant tenant1 = tenantMapper.selectByPrimaryByOrganize(tenant);
                    payOrders.setTenantid(tenant1.getTenantId());
                    payOrders.setTenantname(tenant1.getTenantName());
                    //查询套餐
                    Combo combo = new Combo();
                    combo.setKcode(tenant1.getOrderType());
                    Combo combo1 = comboMapper.selectByPrimaryByKcode(combo);
                    payOrders.setCombocode(combo1.getKcode());
                    payOrders.setComboname(combo1.getName());
                    payOrders.setPayamount(combo1.getPrice());

                    String[] parents = {"妈妈", "爸爸", "爷爷", "奶奶", "姥姥", "姥爷", "其他"};
                    String[] openidlist = student1.getRoleParents().split(",");
                    int com = 0;
                    for (int i = 0; i < openidlist.length; i++) {
                        if (teacherParent.getOpenid().equals(openidlist[i])) {
                            com = i;
                        }
                    }
                    for (int i = 0; i <= parents.length; i++) {
                        if (com == i) {
                            payOrders.setParentname(student1.getName() + parents[i]);
                        }
                    }
                    //添加年级
                    BaseConfig baseConfig = new BaseConfig();
                    baseConfig.setKcode(student1.getGradeno());
                    BaseConfig baseConfig1 = baseConfigMapper.selectByPrimaryByKcode(baseConfig);
                    payOrders.setBasename(baseConfig1.getLabel());
                    payOrders.setBasecode(baseConfig1.getKcode());
                    payOrders.setGoodsorder(s);
                    int insertSelective = payOrdersMapper.insertSelective(payOrders);
                }
            }
        }
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            Map<String, String> qdData = new HashMap<String, String>();
            qdData.put("appId", "wx4c1b026545f7722f");//静态
            qdData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));//动态
            qdData.put("nonceStr", UUID.randomUUID().toString());//静态
            qdData.put("package", "prepay_id=" + resp.get("prepay_id"));//静态
            qdData.put("signType", "MD5");//静态
            String sign = WXPayUtil.generateSignature(qdData, config.getKey(), WXPayConstants.SignType.MD5);
            qdData.put("paySign", sign);
            System.out.println(JSON.toJSON(qdData));
            System.err.println(new Date().getTime() / 1000);

            return new Result(true, "1", "", qdData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false);
    }

    //修改学生缴费状态
    @RequestMapping("/craetePayUpdate")
    public String craetePayUpdate(HttpServletRequest request) throws Exception {
        ServletInputStream inputStream = request.getInputStream();
        StringBuffer buf = new StringBuffer();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            buf.append(s);
        }
        in.close();
        inputStream.close();
        System.err.println(buf);
        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(String.valueOf(buf));
        PayOrders payOrders = new PayOrders();

//        Map<String, String> stringStringMap = new HashMap<>();
//        stringStringMap.put("openid","o0fM1w8QJwxPa26YrpGtz7lh1Cdo");
//        stringStringMap.put("transaction_id","123");
//        stringStringMap.put("out_trade_no","20211617172221681");

        Parent parent = new Parent();
        parent.setOpenid(stringStringMap.get("openid"));
        Parent parent1 = parentMapper.selectByPrimaryByOpenid(parent);
        //查询学生信息返回
        Student student = new Student();
        student.setBindcode(parent1.getCurrentcode());
        Student student1 = studentMapper.selectByPrimaryByCurrentCode(student);
        //修改华栖云数据先登录
        String token_url = "https://yjapp.h5.kecheng.zhixue100.com.cn/userapi/v1/loginbycode?account=" + student1.getBindcode() + "&password=Klmb321hbwx&tenant_id=" + student1.getOrganize() + "&bindcode=" + student1.getBindcode();
        net.sf.json.JSONObject access_token = httpsRequestToJsonObject(token_url, "POST", null);
        String data1 = access_token.getString("params");
        com.alibaba.fastjson.JSONObject jsondata = JSON.parseObject(data1);
        String token = jsondata.getString("token");
//      System.err.println(token);
        //查询租户
        Tenant tenant = new Tenant();
        tenant.setTenantId(student1.getOrganize());
        Tenant tenant1 = tenantMapper.selectByPrimaryByOrganize(tenant);
        //查询套餐
        Combo combo = new Combo();
        combo.setKcode(tenant1.getOrderType());
        Combo combo1 = comboMapper.selectByPrimaryByKcode(combo);
        //添加支付失效时间
        switch (combo1.getComboType()) {
            case 0:
                payOrders.setExpiretime(plusDay(30));
                break;
            case 1:
                payOrders.setExpiretime(plusDay(90));
                break;
            case 2:
                payOrders.setExpiretime(plusDay(365));
                break;
            case 3:
                payOrders.setExpiretime(plusDay(3));
                break;
        }
//        HttpClient client = HttpClients.createDefault();
//        // 修改华栖云支付状态
//        String url = "https://yjapi.kecheng.zhixue100.com.cn/userapi/v1/memberupdate/" + parent1.getCurrentcode();
//        HttpPost post = new HttpPost(url);
//        JSONObject jsonObject = null;
//        try {
//            JSONObject json = new JSONObject();
//            json.put("pay_status", 1);
//            long time = payOrders.getExpiretime().getTime();
//            int n = (int) (time /1000);
//            json.put("expire", n);
//            StringEntity s2 = new StringEntity(json.toString());
//            s2.setContentEncoding("UTF-8");
//            s2.setContentType("application/json");
//            post.setEntity(s2);
//            post.addHeader("Authorization", "Bearer " + token);
//            HttpResponse res = client.execute(post);
//            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
//                jsonObject = JSONObject.parseObject(result);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        System.err.println(jsonObject);
//        if (jsonObject.get("message").equals("编辑用户成功")) {
            //商户订单号
            payOrders.setGoodsorder(stringStringMap.get("out_trade_no"));
            //腾讯返回订单号
            payOrders.setWeixinorder(stringStringMap.get("transaction_id"));
            //微信用户唯一标识
            payOrders.setOpenid(stringStringMap.get("openid"));
            //修改用户为支付用户
            payOrders.setPaytype("1");
            //修改学生表学生支付状态
            student1.setPayStatus(1);
            //修改学生表之支付状态
            int updateByPrimaryKeySelective = studentMapper.updateByPrimaryKeySelective(student1);
            //修改订单表支付状态
            int insertSelective = payOrdersMapper.updateByPrimaryKeySelectiveOpenidAndGoodorder(payOrders);
            //返回微信成功信息xml格式
            Map<String, String> map = new HashMap<>();
            map.put("return_code","SUCCESS");
            map.put("return_msg","OK");
            String s1 = WXPayUtil.mapToXml(map);
            return s1;
//        }
//        //不成功返回空
//        return "";
    }


    /*
     * 如果是小数，保留两bai位，非小数，保留整数
     * @param number
     */
    public static String getDoubleString(double number) {

        String numberStr;

        if (((int) number * 1000) == (int) (number * 1000)) {

//如果是一个整数

            numberStr = String.valueOf((int) number);

        } else {

            DecimalFormat df = new DecimalFormat("######0.00");

            numberStr = df.format(number);

        }

        return numberStr;

    }


    public Date plusDay(int day){
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(d);
        System.out.println("现在的日期是：" + currdate);

        Calendar ca = Calendar.getInstance();
        ca.setTime(d);
        ca.add(Calendar.DATE, day);// num为增加的天数，可以改变的
        d = ca.getTime();
//        String enddate = format.format(d);
//        System.out.println("增加天数以后的日期：" + enddate);
        return d;
    }


    public static JSONObject doPost(JSONObject date) {
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = "http://192.168.1.101:8080/getJson";
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(date.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "text/xml");
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject;
    }

}
